package com.tkm.advancedFunctions.sequences

fun main() {
    val list = listOf(1, 2, 3, 4, 5, 6)

    list.asSequence()
        .filter { it % 2 == 0 }
        .map { it * 2 }
        .forEach { println(it) }

    list.asSequence()
        .flatMap { (0 until it).asSequence() }
        .joinToString()
        .let { println(it) }

    for (e in list) {
        println(e)
    }

    for (i in list.indices) {
        println("$i: ${list[i]}")
    }

    for (i in 0 until list.size) {
        println("$i: ${list[i]}")
    }

    for ((i, e) in list.withIndex()) {
        println("$i: $e")
    }

    list.forEach {
        if (it % 2 == 0) {
            //  相当于continue
            return@forEach
        }
        println(it)
    }

    val newList = list.flatMap { ArrayList<String>(it) }

    list.filter { it % 2 == 0 }

    list.asSequence()
        .filter { it % 2 == 0 }

    list.asSequence()
        .map { it * 2 + 1 }

    list.asSequence()
        .flatMap { (0 until it).asSequence() }
        .joinToString("")
        .let(::println)

    //  fold：相比于reduce，提供一个初始值
    list.fold(0) { prev, current -> prev + current }
    list.reduce { prev, current -> prev + current }

    list.fold(StringBuilder()) { prev, current -> prev.append(current) }
        .let(::println)
}
